package org.ydeity.lucene.repository.support;

import org.apache.lucene.search.Query;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.ydeity.lucene.core.LuceneOperations;
import org.ydeity.lucene.repository.LuceneRepository;

import java.io.Serializable;
import java.util.Optional;

public class SimpleLuceneRepository<T, ID extends Serializable> implements LuceneRepository<T,ID> {

    protected LuceneOperations luceneOperations;

    protected Class<T> entityClass;

    public SimpleLuceneRepository(LuceneOperations luceneOperations){
        this.setLuceneOperations(luceneOperations);
    }

    public void setLuceneOperations(LuceneOperations luceneOperations) {
        this.luceneOperations = luceneOperations;
    }

    @Override
    public Iterable<T> search(Query query) {
        return luceneOperations.queryForObject(entityClass,query,100);
    }

    @Override
    public Page<T> search(Query query, Pageable pageable) {
        return luceneOperations.search(entityClass,query,pageable);
    }

    @Override
    public <S extends T> S save(S s) {
        luceneOperations.doInsert(s);
        return s;
    }

    @Override
    public <S extends T> Iterable<S> saveAll(Iterable<S> iterable) {
        return null;
    }

    @Override
    public Optional<T> findById(ID id) {
        return luceneOperations.getById(entityClass,id);
    }

    @Override
    public boolean existsById(ID id) {
        Optional<T> optional = luceneOperations.getById(entityClass, id);
        return optional.isPresent();
    }

    @Override
    public Iterable<T> findAll() {
        return null;
    }

    @Override
    public Iterable<T> findAllById(Iterable<ID> iterable) {
        return null;
    }

    @Override
    public long count() {
        return luceneOperations.count(entityClass,"id");
    }

    @Override
    public void deleteById(ID id) {
        luceneOperations.doDelete(entityClass,id);
    }

    @Override
    public void delete(T t) {
        luceneOperations.delete(t);
    }

    @Override
    public void deleteAll(Iterable<? extends T> iterable) {
        luceneOperations.deleteAll(iterable,entityClass);
    }

    @Override
    public void deleteAll() {
        luceneOperations.deleteAll(entityClass);
    }
}
